import json
import os

import logzero
import pika
from logzero import logger
import json
import config
import utils
import weibo_one
import bilibli_one
import time
current_module = os.path.splitext(os.path.basename(__file__))[0]

logzero.logfile(f"/tmp/{current_module}.log", maxBytes=30_000_000, backupCount=3, encoding='utf-8')

def main():
    credentials = pika.PlainCredentials(config.RABBITMQ_USER, config.RABBITMQ_PASSWORD)
    connection = pika.BlockingConnection(
        pika.ConnectionParameters(config.RABBITMQ_HTOS, config.RABBITMQ_POST, '/', credentials))
    channel = connection.channel()
    channel.queue_declare(queue='reptole', durable=True)
    channel.basic_consume(callback, queue='reptole', no_ack=True)
    print(' [*] Waiting for messages. To exit press CTRL+C')
    channel.start_consuming()


def callback(ch, method, properties, body):
    logger.info("[x] Received %r" % body)
    db = utils.get_mongo_collection('url_insert_fail')

    rabbitInfo = json.loads(body)
    status=False
    if rabbitInfo['type'] == 'weibo':
        time.sleep(10)
        status, data=weibo_one.main(rabbitInfo['key'], rabbitInfo['username'],rabbitInfo['theme_id'],rabbitInfo['tag'])

    if rabbitInfo['type'] == 'bilibili':
        status,data = bilibli_one.main(rabbitInfo['key'], rabbitInfo['username'],rabbitInfo['theme_id'])
    # print(status)
    if status:
        # 不进阿章的表　　直接进入队列
        # db.insert(data)

        insert_rabbit(data)
        logger.info('进入rabbit')

    else:
        # 放弃的东西要记录
        logger.info('放弃 存入mongo表no_work_by_input')
        db.insert({'type':rabbitInfo['type'] ,'key':rabbitInfo['key'],'theme_id':rabbitInfo['theme_id'],'time':time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()),'admin': rabbitInfo['username']})
        insert_rabbit_for_again(rabbitInfo)
def insert_rabbit(mysql_format):
    credentials = pika.PlainCredentials(config.RABBITMQ_USER, config.RABBITMQ_PASSWORD)
    connection = pika.BlockingConnection(
        pika.ConnectionParameters(config.RABBITMQ_HTOS, config.RABBITMQ_POST, '/', credentials))
    channel = connection.channel()

    # 声明queue
    channel.queue_declare(queue='ltyy', durable=True)
    # print(type(mysql_format))

    mysql_format_json=json.dumps(mysql_format)
    # print(mysql_format_jso
    # n RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange.
    channel.basic_publish(exchange='',
                          routing_key='ltyy',
                          body=mysql_format_json)
    logger.info("Sent success!!")

def insert_rabbit_for_again(rabbitInfo):
    credentials = pika.PlainCredentials(config.RABBITMQ_USER, config.RABBITMQ_PASSWORD)
    connection = pika.BlockingConnection(
        pika.ConnectionParameters(config.RABBITMQ_HTOS, config.RABBITMQ_POST, '/', credentials))
    channel = connection.channel()

    # 声明queue
    channel.queue_declare(queue='reptole', durable=True)
    # print(type(mysql_format))

    mysql_format_json = json.dumps(rabbitInfo)
    # print(mysql_format_jso
    # n RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange.
    channel.basic_publish(exchange='',
                          routing_key='reptole',
                          body=mysql_format_json)
    logger.info("重新写入rabbit!!")
if __name__ == '__main__':

    main()
    # a=weibo_one.main('https://weibo.com/6224836870/F6FYw3m1m?from=page_1005056224836870_profile&wvr=6&mod=weibotime&type=comment#_rnd1520330547242',
    #                'username', '12',[])
    # print(a)